import {Interceptor} from "../../core/Interceptor";
import {Ctx} from "../../index";
import {_} from "../../util/UtilTs";

const expressjwt = require('express-jwt');
const jwt = require('jsonwebtoken');

export class JWTAuth extends Interceptor{
    static create =(opts:Partial<JWTAuth>)=> new JWTAuth(opts);
    secret = "secret";
    middleware;
    validator; //权限控制回调;

    static jwt = jwt;
    static sign;

    constructor(opts:Partial<JWTAuth> = {}) {
        super();
        _.merge(this, opts);
        this.middleware = expressjwt(this);
        JWTAuth.sign = (obj) => jwt.sign(obj, this.secret);
    }

    before(ctx:Ctx){
        const self = this;
        const { req , res } = ctx;
        this.middleware(req,res,function (err) {
            let role = {
                name:'guest',
                id:-1,
            }; //默认为游客
            if(err){ //没有 tocken ， 当游客处理
                //console.log("err",err);
            }
            else {
                ctx.user = req.user;
                role = ctx.role = ctx.user.role;
            }
            //查询权限并控制
            self.validator(ctx,role);
        });
    }




}





